package org.jeecgframework.web.controller;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsServiceServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyEquipmentSpareServiceI;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.pojo.vo.EquipInfo;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 设备以及备件信息
 * @date 2016-03-22 15:13:54
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyEquipmentSpareController")
public class ZyEquipmentSpareController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(ZyEquipmentSpareController.class); // NOPMD by dzqThinkpad on 16-4-1 下午3:02

    @Autowired
    private ZyEquipmentSpareServiceI zyEquipmentSpareService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ZyCommonService zyCommonService;
    @Autowired
    private CbsServiceServiceI cbsServiceService;


    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 设备以及备件信息列表 页面跳转
     */
    @RequestMapping(params = "zyEquipmentSpare")
    public ModelAndView zyEquipmentSpare(HttpServletRequest request) {
        return new ModelAndView("com/zybk/zy_equipment_spare/zyEquipmentSpareList");
    }

    /**
     * 设备以及备件信息列表 datagrid
     */
    @RequestMapping(params = "datagrid")
    public void datagrid(ZyEquipmentSpareEntity zyEquipmentSpare, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(ZyEquipmentSpareEntity.class, dataGrid);
        //影院查看页 设备列表
        String cmViewPageSn = oConvertUtils.getString(request.getParameter("cmViewPageSn"));
        if (StringUtil.isNotEmpty(cmViewPageSn)) {
            cq.eq("sn", cmViewPageSn);
        }
        if (StringUtil.isEmpty(zyEquipmentSpare.getSn())) {
            //影院查看页 设备列表
            String belongCinemaId = oConvertUtils.getString(request.getParameter("belongCinemaId"));
            if (StringUtil.isNotEmpty(belongCinemaId)) {
                cq.eq("zyCinema.id", belongCinemaId);
            }
        }
        if ("1".equals(oConvertUtils.getString(request.getParameter("isInService")))) {
            cq.gt("repairEndDate", new Date());
        }
        cq.eq("isSpare", false);//默认条件，不查询备件

        String typeDescs = oConvertUtils.getString(request.getParameter("typeDescs"));  //备件类型
        if (StringUtil.isNotEmpty(typeDescs)) {
            String sql = "SELECT\n" +
                    "\tid\n" +
                    "FROM\n" +
                    "\tzy_equipment_type\n" +
                    "WHERE\n" +
                    "\tparent_id IN (\n" +
                    "\t\tSELECT\n" +
                    "\t\t\tid\n" +
                    "\t\tFROM\n" +
                    "\t\t\tzy_equipment_type\n" +
                    "\t\tWHERE\n" +
                    "\t\t\ttype_desc LIKE '%" + typeDescs + "%'\n" +
                    "\t)";
            List<Map<String, Object>> zyEquipmentTypeEntity = systemService.findForJdbc(sql);
            if (zyEquipmentTypeEntity.size() > 0) {
                List<String> list = new ArrayList<>();
                for (Map<String, Object> map : zyEquipmentTypeEntity) {
                    list.add(map.get("id").toString());
                }
                cq.in("type.id", list.toArray());
            }
        }
        String item = oConvertUtils.getString(request.getParameter("item"));  //备件序列号
        if (StringUtil.isNotEmpty(item)) {
            cq.eq("sn", item);
        }

        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEquipmentSpare, request.getParameterMap());
        try {
            cq.add();
            this.zyEquipmentSpareService.getDataGridReturn(cq, true);
            for (ZyEquipmentSpareEntity zyEs : (List<ZyEquipmentSpareEntity>) dataGrid.getResults()) {
                if (zyEs != null) {
                    //设置省市 同时 显示
                    String tsTerritoryVal = "";
                    if (zyEs.getTsTerritory() != null && null != zyEs.getTsTerritory().getTSTerritory()) {
                        tsTerritoryVal = zyEs.getTsTerritory().getTSTerritory().getTerritoryName() + "," + zyEs.getTsTerritory().getTerritoryName();
                    } else if (zyEs.getTsTerritory() != null) {
                        tsTerritoryVal = zyEs.getTsTerritory().getTerritoryName();
                    }
                    zyEs.setTsTerritoryVal(tsTerritoryVal);
                }
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 备件序列号查询功能信息列表 datagridBj
     */
    @RequestMapping(params = "datagridBj")
    public void datagridBj(ZyEquipmentSpareEntity zyEquipmentSpare, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        boolean flag = false;
        if (StringUtil.isEmpty(zyEquipmentSpare.getItem()) || StringUtil.isEmpty(request.getParameter("typeDescs"))) {
            flag = true;//页面 查询条件为空不做查询
        }
        if (!flag) {
            CriteriaQuery cq = new CriteriaQuery(ZyEquipmentSpareEntity.class, dataGrid);
            cq.add(Restrictions.eq("isSpare",false));//默认条件，不查询备件


            String sql1 = "select top_item_sn as itemsn from zy_equipment_spare zy where 1=1 and is_spare = 1 ";
            //影院查看页 设备列表
            String item = oConvertUtils.getString(request.getParameter("item"));
            if (StringUtil.isNotEmpty(item)) {
                sql1 += " and zy.sn = '" +item+"'" ;
            }
            String typeDescs = oConvertUtils.getString(request.getParameter("typeDescs"));  //备件类型
            if (StringUtil.isNotEmpty(typeDescs)) {
                String sql = "SELECT\n" +
                        "\t\t\tid\n" +
                        "\t\tFROM\n" +
                        "\t\t\tzy_equipment_type\n" +
                        "\t\tWHERE\n" +
                        "\t\t\ttype_desc LIKE '%" + typeDescs + "%' ";
                List<Map<String, Object>> zyEquipmentTypeEntity = systemService.findForJdbc(sql);
                if (zyEquipmentTypeEntity.size() > 0) {
                    sql1 += " and type in (";
                    for (int i = 0; i < zyEquipmentTypeEntity.size(); i++) {
                        if (i == zyEquipmentTypeEntity.size() - 1) {
                            sql1 += "'" + zyEquipmentTypeEntity.get(i).get("id") + "'";
                        } else {
                            sql1 += "'" + zyEquipmentTypeEntity.get(i).get("id") + "',";
                        }
                    }
                    sql1 += " 	) ";
                }
            }
            //查询top_item_sn
            List<Map<String, Object>> item_sn = systemService.findForJdbc(sql1);
            if (item_sn.size() > 0) {
                Object itemsn = item_sn.get(0).get("itemsn");
                if (StringUtil.isNotEmpty(itemsn)) {
                    cq.add(Restrictions.eq("sn", itemsn));

                    //查询条件组装器
                    this.zyEquipmentSpareService.getDataGridReturn(cq, true);
                    for (ZyEquipmentSpareEntity zyEs : (List<ZyEquipmentSpareEntity>) dataGrid.getResults()) {
                        if (zyEs != null) {
                            //设置省市 同时 显示
                            String tsTerritoryVal = "";
                            if (zyEs.getTsTerritory() != null && null != zyEs.getTsTerritory().getTSTerritory()) {
                                tsTerritoryVal = zyEs.getTsTerritory().getTSTerritory().getTerritoryName() + "," + zyEs.getTsTerritory().getTerritoryName();
                            } else if (zyEs.getTsTerritory() != null) {
                                tsTerritoryVal = zyEs.getTsTerritory().getTerritoryName();
                            }
                            zyEs.setTsTerritoryVal(tsTerritoryVal);
                        }
                    }

                }else{
                    dataGrid.setResults(new ArrayList<>());
                }
            }else{
                dataGrid.setResults(new ArrayList<>());
            }

        } else {
            dataGrid.setResults(new ArrayList<>());
        }

        TagUtil.datagrid(response, dataGrid);
    }


    /**
     * 设备信息查询列表 页面跳转
     */
    @RequestMapping(params = "zyEquipmentSpareInfo")
    public ModelAndView zyEquipmentSpareInfo(HttpServletRequest request) {
        return new ModelAndView("com/zybk/zy_equipment_spare/zyEquipmentSpareInfoList");
    }

    /**
     * 设备信息查询 列表 datagrid
     */
    @RequestMapping(params = "datagridOfEsInfoList")
    public void datagridOfEsInfoList(ZyEquipmentSpareEntity zyEquipmentSpare, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(ZyEquipmentSpareEntity.class, dataGrid);
        cq.eq("isSpare", false);//默认条件 ，不查询备件
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEquipmentSpare, request.getParameterMap());
        try {
        	if (StringUtil.isNotEmpty(zyEquipmentSpare.getItem())) {
        		cq.eq("item", zyEquipmentSpare.getItem());
        	}
            cq.add();
            Map<String, String[]> parameterMap = request.getParameterMap();
            boolean flag = false;
            for (String key : parameterMap.keySet()) {
                if (key.equals("sn")
                        || key.equals("bpNo")
                        || key.equals("tsTerritory.territoryName")
                        || key.equals("tsTerritory.TSTerritory.territoryName")
                         || key.equals("item")
                        || key.equals("zyCinema.name")) {
                    if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
//						System.out.println(key + ":>" + parameterMap.get(key)[0] + "<");
                        flag = true;//页面 4个查询条件，如果其中一个有值，那么根据条件查询，否则不做查询
                        break;
                    }
                }
            }
            if (flag) {
                this.zyEquipmentSpareService.getDataGridReturn(cq, true);
                for (ZyEquipmentSpareEntity zyEs : (List<ZyEquipmentSpareEntity>) dataGrid.getResults()) {
                    if (zyEs != null) {
                        //设置省市 同时 显示
                        String tsTerritoryVal = "";
                        if (zyEs.getTsTerritory() != null && null != zyEs.getTsTerritory().getTSTerritory()) {
                            tsTerritoryVal = zyEs.getTsTerritory().getTSTerritory().getTerritoryName() + "," + zyEs.getTsTerritory().getTerritoryName();
                        } else if (zyEs.getTsTerritory() != null) {
                            tsTerritoryVal = zyEs.getTsTerritory().getTerritoryName();
                        }
                        zyEs.setTsTerritoryVal(tsTerritoryVal);
                    }
                }
            } else {
                dataGrid.setResults(new ArrayList<>());
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 设备详情页 datagridForTopItem
     */
    @RequestMapping(params = "datagridForTopItem")
    public void datagridForTopItem(ZyEquipmentSpareEntity zyEquipmentSpare, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(ZyEquipmentSpareEntity.class, dataGrid);
        //设备详情页传来的
        String topItemSn = request.getParameter("topItemSn");
        cq.eq("isSpare", true);
        if (null != topItemSn && !topItemSn.equals("")) {
            cq.eq("topItemSn", topItemSn);
        } else {
            cq.eq("topItemSn", "8888888888888888888888");
        }
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEquipmentSpare, request.getParameterMap());
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.zyEquipmentSpareService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 添加设备以及备件信息
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(ZyEquipmentSpareEntity zyEquipmentSpare, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "设备[" + zyEquipmentSpare.getSn() + "]添加成功";
        try {
            zyEquipmentSpare.setHouse(zyEquipmentSpare.getHouse().getId().equals("") ? null : zyEquipmentSpare.getHouse());
            zyEquipmentSpare.setTsDepart(zyEquipmentSpare.getTsDepart().getId().equals("") ? null : zyEquipmentSpare.getTsDepart());
            zyEquipmentSpare.setZyCinema(zyEquipmentSpare.getZyCinema().getId().equals("") ? null : zyEquipmentSpare.getZyCinema());
            zyEquipmentSpare.setIsSpare(false);
            zyEquipmentSpare.setIsHadInspection("0");
            /**update by xiu 20160722 因为去除了设备的省市字段的添加和编辑，所以在添加的时候根据所选的影院设置省市字段*/
            if (null != zyEquipmentSpare.getZyCinema() && null != zyEquipmentSpare.getZyCinema().getId() && !zyEquipmentSpare.getZyCinema().getId().equals("")) {
                ZyCinemaEntity zyCm = systemService.getEntity(ZyCinemaEntity.class, zyEquipmentSpare.getZyCinema().getId());
                zyEquipmentSpare.setTsTerritory(zyCm.getProvince());
            }
            if (null != zyEquipmentSpare.getTsDepart()) {
                zyEquipmentSpare.setBpNo(((TSDepart) systemService.getEntity(TSDepart.class, zyEquipmentSpare.getTsDepart().getId())).getBpCode());//bpNo不可新增或修改，由选择的机构更新
            }
            //18年8月8号，发现设备中字段为空字符串，导致编辑出错。故修改为null
            zyEquipmentSpare.setSendSign(zyEquipmentSpare.getSendSign().getId().equals("") ? null : zyEquipmentSpare.getSendSign());
            zyEquipmentSpareService.save(zyEquipmentSpare);
            ZyEquipmentSpareHisEntity zyEquipmentSpareHis = new ZyEquipmentSpareHisEntity();
            MyBeanUtils.copyBeanNotNull2Bean(zyEquipmentSpare, zyEquipmentSpareHis);
            zyEquipmentSpareHis.setBusId(zyEquipmentSpare.getId());
            zyEquipmentSpareHis.setDataStatus("create");
            zyEquipmentSpareService.save(zyEquipmentSpareHis);
        } catch (Exception e) {
            e.printStackTrace();
            message = "设备[" + zyEquipmentSpare.getSn() + "]添加失败";
        }
        systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        j.setMsg(message);
        return j;
    }

    /**
     * 更新设备以及备件信息
     *
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(ZyEquipmentSpareEntity zyEquipmentSpare, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        ZyEquipmentSpareEntity t = zyEquipmentSpareService.get(ZyEquipmentSpareEntity.class, zyEquipmentSpare.getId());
        message = "设备[" + t.getSn() + "]更新成功";
        zyEquipmentSpare.setHouse(zyEquipmentSpare.getHouse().getId().equals("") ? null : zyEquipmentSpare.getHouse());
        zyEquipmentSpare.setTsDepart(zyEquipmentSpare.getTsDepart().getId().equals("") ? null : zyEquipmentSpare.getTsDepart());
        zyEquipmentSpare.setZyCinema(zyEquipmentSpare.getZyCinema().getId().equals("") ? null : zyEquipmentSpare.getZyCinema());
        zyEquipmentSpare.setSendSign(zyEquipmentSpare.getSendSign().getId().equals("") ? null : zyEquipmentSpare.getSendSign());
        /**update by xiu 20160722 因为去除了设备的省市字段的添加和编辑，所以在添加的时候根据所选的影院设置省市字段*/
        if (null != zyEquipmentSpare.getZyCinema() && null != zyEquipmentSpare.getZyCinema().getId() && !zyEquipmentSpare.getZyCinema().getId().equals("")) {
            ZyCinemaEntity zyCm = systemService.getEntity(ZyCinemaEntity.class, zyEquipmentSpare.getZyCinema().getId());
            zyEquipmentSpare.setTsTerritory(zyCm.getProvince());
        } else if (null == zyEquipmentSpare.getZyCinema()) {
            zyEquipmentSpare.setTsTerritory(null);
        }
        if (null != zyEquipmentSpare.getTsDepart()) {
            zyEquipmentSpare.setBpNo(((TSDepart) systemService.getEntity(TSDepart.class, zyEquipmentSpare.getTsDepart().getId())).getBpCode());//bpNo不可新增或修改，由选择的机构更新
        }
        try {
            MyBeanUtils.copyBean2Bean(t, zyEquipmentSpare);
            zyEquipmentSpareService.saveOrUpdate(t);
            ZyEquipmentSpareHisEntity zyEquipmentSpareHis = new ZyEquipmentSpareHisEntity();
            MyBeanUtils.copyBean2Bean(zyEquipmentSpareHis, t);
            zyEquipmentSpareHis.setBusId(t.getId());
            zyEquipmentSpareHis.setDataStatus("update");
            zyEquipmentSpareService.save(zyEquipmentSpareHis);
            // 更新服务单所属影院id
            if (null != zyEquipmentSpare.getZyCinema() && null != zyEquipmentSpare.getZyCinema().getId() && !zyEquipmentSpare.getZyCinema().getId().equals("")) {
            	systemService.updateBySqlString("UPDATE cbs_service set zy_cinema_id = '"+zyEquipmentSpare.getZyCinema().getId()+"' where zy_equipment_spare_id = '" + zyEquipmentSpare.getId() + "' and zy_cinema_id is null");
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "设备[" + t.getSn() + "]更新失败";
        }
        systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        j.setMsg(message);
        return j;
    }

    /**
     * @author xiul
     * 2016-11-18 下午2:50:47
     * Description 设备新增编辑 - 弹出式选择机构 页面跳转
     */
    @RequestMapping(params = "zyChooseOrgsForEs")
    public ModelAndView zyOrgs(HttpServletRequest request) {
        return new ModelAndView("com/zybk/zy_equipment_spare/zyChooseOrgsForEs");
    }

    /**
     * 通过备件序列号查询
     *
     * @return
     */
    @RequestMapping(params = "searchEquipment")
    public ModelAndView searchEquipment() {
        return new ModelAndView("com/zybk/zy_equipment_spare/zySearchEquipment");
    }

    /**
     * @author xiul
     * 2016-11-18 下午2:51:19
     * Description 设备新增编辑 - 弹出式选择机构 datagrid
     */
    @RequestMapping(params = "chooseDepartForEsListDatagrid")
    public void chooseDepartForEsListDatagrid(TSDepart tsDepart, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
        cq.add(Restrictions.or(Restrictions.eq("logicDelete", "0"), Restrictions.isNull("logicDelete")));//基本过滤条件，只查询未删除的数据
        cq.add(Restrictions.eq("orgType", StaticValue.DIC_ORG_TYPE_THIRD_PARTY));//机构类型是第三方
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tsDepart, request.getParameterMap());
        cq.add();
        this.systemService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 设备以及备件信息新增页面跳转
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(ZyEquipmentSpareEntity zyEquipmentSpare, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(zyEquipmentSpare.getId())) {
            zyEquipmentSpare = zyEquipmentSpareService.getEntity(ZyEquipmentSpareEntity.class, zyEquipmentSpare.getId());
            req.setAttribute("zyEquipmentSparePage", zyEquipmentSpare);
        }
        return new ModelAndView("com/zybk/zy_equipment_spare/zyEquipmentSpare-add");
    }


    /**
     * 设备以及备件信息编辑页面跳转
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(ZyEquipmentSpareEntity zyEquipmentSpare, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(zyEquipmentSpare.getId())) {
            zyEquipmentSpare = zyEquipmentSpareService.getEntity(ZyEquipmentSpareEntity.class, zyEquipmentSpare.getId());
            req.setAttribute("zyEquipmentSparePage", zyEquipmentSpare);
        }
        return new ModelAndView("com/zybk/zy_equipment_spare/zyEquipmentSpare-update");
    }

    /**
     * @author xiul
     * 2016-3-28 下午5:57:10
     * Description 查看设备详细
     */
    @RequestMapping(params = "goView")
    public ModelAndView goView(ZyEquipmentSpareEntity zyEquipmentSpare, HttpServletRequest req) {
        if (zyEquipmentSpare.getId() != null) {
            zyEquipmentSpare = zyEquipmentSpareService.getEntity(ZyEquipmentSpareEntity.class, zyEquipmentSpare.getId());
            req.setAttribute("zyEquipmentSparePage", zyEquipmentSpare);
            TSType tsType = zyCommonService.queryTsType(StaticValue.DIC_SERVER_STATE, zyEquipmentSpare.getServerState());
            if (tsType != null) {
                zyEquipmentSpare.setServerStateVal(tsType.getTypename());
            }
            //获取sla信息
            List<Map<String, Object>> slaList1 = cbsServiceService.getAllSLABySn(zyEquipmentSpare.getSn());
            String supplement = "";
            if (slaList1.size() > 0) {
                supplement = (String) slaList1.get(0).get("supplement");
                if (StringUtil.isNotEmpty(supplement)) {
                    String[] suppmentSplit = supplement.split(",");
                    StringBuffer stringBuffer = new StringBuffer();
                    for (int i = 0; i < suppmentSplit.length; i++) {
                        if (!" ".equals(suppmentSplit[i])) {
                            stringBuffer.append(suppmentSplit[i] + ",");
                        }
                    }
                    if (stringBuffer.toString().length() > 1) {
                        slaList1.get(0).put("supplement", stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1));
                    } else if (stringBuffer.toString().length() == 1) {
                        slaList1.get(0).put("supplement", stringBuffer.toString());
                    } else {
                        slaList1.get(0).put("supplement", null);
                    }
                }
                req.setAttribute("slaList1", slaList1.get(0));
            }
            //根据设备sn号，查找最近一次维修的软件版本信息   2018/5/8添加
            String sql = "SELECT\n" +
                    "\tIFNULL(\n" +
                    "\t\tDATE_FORMAT(\n" +
                    "\t\t\tMAX(sc.create_date),\n" +
                    "\t\t\t'%Y-%m-%d'\n" +
                    "\t\t),\n" +
                    "\t\t''\n" +
                    "\t) AS vcreate_date,\n" +
                    "\tMAX(\n" +
                    "\t\tIFNULL(sc.REPAIR_AFTER1, '')\n" +
                    "\t) AS v1,\n" +
                    "\tMAX(\n" +
                    "\t\tIFNULL(sc.REPAIR_AFTER2, '')\n" +
                    "\t) AS v2\n" +
                    "FROM\n" +
                    "\tcbs_service cbs\n" +
                    "LEFT JOIN CBS_SCENE_REPORT sc ON sc.sn = cbs.sn\n" +
                    "WHERE cbs.sn = '" + zyEquipmentSpare.getSn() + "'";
            List<Map<String, Object>> list = systemService.findForJdbc(sql);
            if (list.size() > 0) {
                if (StringUtil.isNotEmpty(list.get(0).get("v1"))) {
                    zyEquipmentSpare.setV1(list.get(0).get("v1").toString());  //放映机软件版本
                }
                if (StringUtil.isNotEmpty(list.get(0).get("v2"))) {
                    zyEquipmentSpare.setV2(list.get(0).get("v2").toString()); //ICP/TI/ICMP软件版本
                }
                if (StringUtil.isNotEmpty(list.get(0).get("vcreate_date"))) {
                    zyEquipmentSpare.setVcreateDate(list.get(0).get("vcreate_date").toString()); //版本更新时间
                }
            }

        }
        return new ModelAndView("com/zybk/zy_equipment_spare/zyEquipmentSpare-view");
    }

    /**
     * @param param validataForm ajaxUrl 参数
     * @author xiul
     * 2016-6-16 下午3:30:22
     * Description 检查SN唯一性
     */
    @ResponseBody
    @RequestMapping(params = "checkSnUnique")
    public ValidForm checkSnUnique(@RequestParam(value = "param", defaultValue = "") String param,
                                   @RequestParam(value = "esId", defaultValue = "") String esId
    ) {
        ValidForm vf = new ValidForm();
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT COUNT(1) AS total ");
        sql.append(" FROM zy_equipment_spare es");
        sql.append(" WHERE ");
        sql.append(" es.sn = '" + param + "' ");
        if (StringUtil.isNotEmpty(esId)) {
            sql.append(" AND id != '" + esId + "' ");
        }
        int total = zyCommonService.getCountBySql(sql.toString());
        if (total > 0) {
            vf.setStatus(ValidForm.N);
            vf.setInfo("当前SN已经存在");
        }
        return vf;
    }

    /**
     * 首页 快速查询设备 页面跳转
     */
    @RequestMapping(params = "homePageZyEquipmentSpare")
    public ModelAndView homePageZyEquipmentSpare(HttpServletRequest req) {
        req.setAttribute("sn", oConvertUtils.getString(req.getParameter("sn")));
        return new ModelAndView("com/zybk/zy_equipment_spare/zyEquipmentSpareListOfQuickSearch");
    }

    /**
     * 首页 快速查询设备 datagrid
     */
    @RequestMapping(params = "datagridOfQuickSearch")
    public void datagridOfQuickSearch(ZyEquipmentSpareEntity zyEquipmentSpare, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(ZyEquipmentSpareEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEquipmentSpare, request.getParameterMap());
        try {
            //本页传来的
            String sn_now = oConvertUtils.getString(request.getParameter("sn"));
            if (StringUtil.isNotEmpty(sn_now)) {
                cq.eq("sn", sn_now);
            } else {
            //快速查询传来的
            String sn = oConvertUtils.getString(request.getParameter("quickSn"));
            if (StringUtil.isNotEmpty(sn)) {
                cq.eq("sn", sn);
            }
            }
            cq.eq("isSpare", false);//默认条件，不查询备件
            cq.add();
            this.zyEquipmentSpareService.getDataGridReturn(cq, true);
            for (ZyEquipmentSpareEntity zyEs : (List<ZyEquipmentSpareEntity>) dataGrid.getResults()) {
                if (zyEs != null) {
                    //设置省市 同时 显示
                    String tsTerritoryVal = "";
                    if (zyEs.getTsTerritory() != null && null != zyEs.getTsTerritory().getTSTerritory()) {
                        tsTerritoryVal = zyEs.getTsTerritory().getTSTerritory().getTerritoryName() + "," + zyEs.getTsTerritory().getTerritoryName();
                    } else if (zyEs.getTsTerritory() != null) {
                        tsTerritoryVal = zyEs.getTsTerritory().getTerritoryName();
                    }
                    zyEs.setTsTerritoryVal(tsTerritoryVal);
                }
            }
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        TagUtil.datagrid(response, dataGrid);
    }


    @ResponseBody
    @RequestMapping(params = "getEquipByCinema")
    public List<EquipInfo> getEquipByCinema(String cinemaId) {
        List<EquipInfo> equipList = new ArrayList<EquipInfo>();
        List<ZyEquipmentSpareEntity> equips = zyEquipmentSpareService.findEquipByCinemaId(cinemaId);
        //(ZyEquipmentSpareEntity.class,"zyCinema.id",oConvertUtils.getString(cinemaId)
        for (ZyEquipmentSpareEntity eq : equips) {
            EquipInfo equip = new EquipInfo();
            equip.setId(eq.getId());
            equip.setSn(eq.getSn());
            equip.setBpNo(eq.getBpNo());
            if (eq.getType() != null) {
                equip.setTypeDesc(eq.getType().getTypeDesc());
            }
            equipList.add(equip);
        }
        return equipList;
    }

    /**
     * 导出excel 模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public void exportXlsByT(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
        try {
            @SuppressWarnings("deprecation")
            String templatePath = request.getRealPath("/") + "export/template/FilmRenewalTemplate.xlsx";
            FileUtils.downFile(templatePath, "中影续保.xlsx", response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @author xiul
     * 2016-11-1 下午5:15:32
     * Description 设备变更申请列表页点击SN - 检查SN是否存在
     */
    @ResponseBody
    @RequestMapping(params = "checkEsExistBySn")
    public AjaxJson checkEsExistBySn(String sn) {
        AjaxJson j = new AjaxJson();
        try {
            if (StringUtil.isNotEmpty(sn)) {
                List<ZyEquipmentSpareEntity> ess = systemService.findByProperty(ZyEquipmentSpareEntity.class, "sn", sn);
                if (ess.size() != 0) {
                    j.setObj(ess.get(0).getId());
                } else {
                    message = "SN为[" + sn + "]的设备或备件不存在";
                    j.setSuccess(false);
                }
            } else {
                message = "SN为空";
                j.setSuccess(false);
            }
        } catch (Exception e) {
            j.setSuccess(false);
            message = "查询失败";
            e.printStackTrace();
        }
        j.setMsg(message);
        return j;
    }

    @RequestMapping(params = "bpType")
    @ResponseBody
    public Map getBpTypeWithBpNo(String bpNo) {
        Map result = new HashMap();
        result.put("bpType", zyEquipmentSpareService.checkBP(oConvertUtils.getString(bpNo)));
        return result;
    }

    @RequestMapping(params = "wxRepairList")
    public ModelAndView goWxRepairList(String sn) {
        ModelAndView mv = new ModelAndView("com/wx/repair_query/wx_repair_list");
        List<ZyEquipmentSpareEntity> esList = systemService.findHql("from ZyEquipmentSpareEntity where isSpare = false and sn = ?", sn);
        mv.addObject("equip", esList);
        mv.addObject("sn", sn);
        String logo = "bg-logo.jpg";
        if (esList.size() > 0) {
            if (esList.get(0).getType() != null && esList.get(0).getType().getEquipmentType() != null) {
                String tempLogo = esList.get(0).getType().getEquipmentType().getLogo();
                if (StringUtil.isNotEmpty(tempLogo)) {
                    logo = tempLogo;
                }
            }
        }
        mv.addObject("logo", logo);
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < esList.size(); i++) {
            Calendar cal = Calendar.getInstance();
            if(esList.get(i)!=null && StringUtil.isNotEmpty(esList.get(i).getRepairEndDate())){
                cal.setTime(esList.get(i).getRepairEndDate());
            }
            Calendar date = Calendar.getInstance();
            date.setTime(new Date());
            map.put(esList.get(i).getId(), DateUtils.dateDiff('d', cal, date));
        }
        mv.addObject("map", map);
        return mv;
    }

    @RequestMapping(params = "goWxInspectionList")
    public ModelAndView goWxInspectionList(String sn) {
        ModelAndView mv = new ModelAndView("com/wx/self_service/wx_inspection_list");
        List<ZyEquipmentSpareEntity> esList = systemService.findHql("from ZyEquipmentSpareEntity where isSpare = false and sn = ?", sn);
        mv.addObject("equip", esList);
        mv.addObject("sn", sn);
        String logo = "bg-logo.jpg";
        if (esList.size() > 0) {
            if (esList.get(0).getType() != null && esList.get(0).getType().getEquipmentType() != null) {
                String tempLogo = esList.get(0).getType().getEquipmentType().getLogo();
                if (StringUtil.isNotEmpty(tempLogo)) {
                    logo = tempLogo;
                }
            }
            String sql = "select *from Zy_inspection_plan where equipment_spare_id='" + esList.get(0).getId() + "'and YEAR(ip_plan_date)=YEAR(NOW())";
            List<Map<String, Object>> iPlanList = systemService.findForJdbc(sql);
            mv.addObject("iplanList", iPlanList);
        }
        mv.addObject("logo", logo);
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < esList.size(); i++) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(esList.get(i).getRepairEndDate());
            Calendar date = Calendar.getInstance();
            date.setTime(new Date());
            map.put(esList.get(i).getId(), DateUtils.dateDiff('d', cal, date));

        }

        mv.addObject("map", map);
        //查询所有巡检计划状态
        List<TSType> planStateList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='planState'");
        mv.addObject("planStateList", planStateList);
        return mv;
    }
}
